package com.xdth.sync.util;

import com.xdth.mq.consumer.QueueConsumer;
import jodd.util.StringUtil;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.File;
import java.io.FilenameFilter;
import java.util.*;

/**
 * Created by dy on 17-7-3.
 */
@Component("syncListener")
public class SyncListener {

  final Logger logger = LoggerFactory.getLogger(SyncListener.class);

  @Resource
  private QueueConsumer queueConsumer;

  @Value("#{config['sync.queue']}")
  private String queueName;

  @Value("#{config['sync.data.dir']}")
  private String syncDataDir;
  @Resource
  private SyncExecutor syncExecutor;


  public void startListener() {
    while (true) {
      try {
        Map<String, Object> contentMap = queueConsumer.receiveText(queueName);

        if (null != contentMap && !contentMap.isEmpty()) {

          String syncFileName = (String) contentMap.get("TEXT");
          logger.info("获取消息队列同步信息：[{}]", syncFileName);
          if (StringUtil.isNotEmpty(syncFileName)) {
            if ("ALL".equals(syncFileName)) {
              File syncDirFile = new File(syncDataDir);
              Calendar c = Calendar.getInstance(TimeZone.getTimeZone("GMT+8"));
              c.add(Calendar.DATE, -1);
              final String currentDate = DateFormatUtils.format(c, "yyyyMMdd", TimeZone.getTimeZone("GMT+8"));
              if (syncDirFile.exists()) {
                File[] dataFiles = syncDirFile.listFiles(new FilenameFilter() {
                  @Override
                  public boolean accept(File dir, String name) {
                    if (StringUtil.isNotEmpty(name) && name.indexOf(currentDate) > -1 && name.endsWith(SyncExecutor.AVL)) {
                      return true;
                    }
                    return false;
                  }
                });
                for (File dataFile : dataFiles) {
                  logger.info("文件：【{}】", dataFile.getName());
                  syncExecutor.executeSync(dataFile.getName());
                }
              }
            } else {
              String [] fileNames = syncFileName.split(",");
              if (null != fileNames) {
                for (String name: fileNames) {
                  if (StringUtil.isNotEmpty(name)) {
                    name=name.trim();
                    if (!name.endsWith("AVL")) {
                      name+=".AVL";
                    }
                    File file = new File(syncDataDir+ name);
                    if (file.exists() && file.isFile()) {
                      logger.info("文件：【{}】", syncFileName);
                      syncExecutor.executeSync(file.getName());
                    }
                  }
                }
              }

            }
          }
        }
      } catch (Exception e) {
        logger.error("获取队列失败", e);
      }
    }
  }


}
